#coding=utf8
# Copyright (c) 2016 Tinydot. inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import random
import numpy as np
from PIL import Image


COLOR_DISTINCT = {
    "white":           (255, 255, 255),
    "red":             (255, 0,   0),
    "green":           (0, 255, 0),
    "blue":            (0, 0, 255),
    "snow":            (255, 250, 250),
    "paleturquoise":   (187, 255, 255),
    "gainsboro":       (220, 220, 220),
    "cadetblue":       (152, 245, 255),
    "linen":           (250, 240, 230),
    "turquoise":       (0, 245, 255),
    "lavender":        (230, 230, 250),
    "aquamarine":      (102, 205, 170),
    "black":           (0, 0, 0),
    "grey":            (190, 190, 190),
    "seahreen":        (84, 255, 159),
    "lightgray":       (211, 211, 211),
    "skyblue":         (135, 206, 235),
    "olivedrab":       (192, 255, 62),
    "gold":            (255, 215, 0),
    "burlywood":       (222, 184, 135),
    "wheat":           (238, 216, 174),
    "tomato":          (255, 99, 71),
    "tan":             (205, 133, 63),
    "hotpink":         (255, 105, 180),
    "firebrick":       (238, 44, 44),
}


def rand_choose(data_list):
    idx = random.randint(0, len(data_list)-1)
    return data_list[idx]


def random_color(exclude=None):
    _ex_key = exclude or []
    if len(_ex_key):
        assert isinstance(_ex_key[0], str), "key error: %s" % exclude
    key = rand_choose([k for k in COLOR_DISTINCT.keys() if k not in _ex_key])
    return COLOR_DISTINCT[key]


def fix_color(index, exclude=None):
    _ex_key = exclude or []
    if len(_ex_key):
        assert isinstance(_ex_key[0], str), "key error: %s" % exclude
    keys = [k for k in COLOR_DISTINCT.keys() if k not in _ex_key]
    keys.sort()
    return COLOR_DISTINCT[keys[index % len(keys)]]


K_RED = "red"
K_BLU = "blue"
K_GRE = "green"
K_BLK = "black"
RED = COLOR_DISTINCT[K_RED]
BLU = COLOR_DISTINCT[K_BLU]
GRE = COLOR_DISTINCT[K_GRE]
BLK = COLOR_DISTINCT[K_GRE]


def ins_numpy_to_dis_image(numpy_data, ignore_color=None):
    assert len(numpy_data.shape) == 2
    ign_color = ignore_color or []
    w, h = numpy_data.shape
    ret_image = np.zeros((w, h, 3)).astype(np.uint8)
    for i, u in enumerate(np.unique(numpy_data)):
        if u == 0:
            continue
        ret_image[numpy_data == u] = fix_color(i, exclude=ign_color)
    return Image.fromarray(ret_image, mode="RGB")

